/**
 * 订单页面的状态数据
 */
import { getOrders, delOrder } from '@/api/ajax'

export default {
   namespaced: true,
   state: {
      orderList: [], // 用户订单
   },
   actions: {
      /* 获取用户订单列表 */
      async getUserOrders(context, username) {
         const { orderList, code } = await getOrders(username)
         if (code) context.commit('SAVE_USER_ORDERLIST', orderList)
      },
      /* 删除一条用户订单 */
      delOrderById(context, orderId) {
         // 删除数据库中对应的订单
         delOrder(Number(orderId))
         context.commit('DEL_ORDER_BY_ID', Number(orderId))
      },
   },
   mutations: {
      /* 保存用户订单列表 */
      SAVE_USER_ORDERLIST(state, orderList) {
         state.orderList = orderList.reverse()
      },
      /* 删除一条用户订单 */
      DEL_ORDER_BY_ID(state, orderId) {
         state.orderList = state.orderList.filter(item => item.id !== orderId)
      },
      /* 完成一条订单 */
      FINISH_ONE_ORDER(state, orderId) {
         const target = state.orderList.find(item => item.id == orderId)
         target.state = 1
      }
   },
   getters: {}
}